<?php


namespace App\Http\Controllers\Supplier;


use App\Http\Controllers\Controller;
use App\Models\BillReport;
use App\Models\MemberQnRisk;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OrderLeasePartial;
use App\Models\OtherWithholdLog;
use App\Models\RechargeLog;
use App\Models\ShopSms;
use App\Models\ShopTrans;
use App\Models\ShopUser;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\AntchainService;
use App\Services\ChargeService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\NotarizeService;
use App\Services\OrderService;
use App\Services\OtherCallbacksService;
use App\Services\OttService;
use App\Services\RadarService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NoticeController extends Controller
{
    public function rechargeNotify(Request $request){
        try{
            $result = $request->all();
            AlipayService::requestLog('供应商充值回调','',$result);
            if($result['trade_status'] == 'TRADE_SUCCESS'){
                DB::beginTransaction();
                $passback_params = urldecode($result['passback_params']);
                $log = RechargeLog::where(['out_trade_no'=>$request['out_trade_no'],'member_id'=>$passback_params])->first();
                $log = obToArray($log);
                if($log){
                    $updateLog = [
                        'trade_no'=>$request['trade_no'],
                        'status'=>RechargeLog::STATUS_SUCCESS,
                        'result'=>json_encode($result),
                    ];
                    RechargeLog::where(['id'=>$log['id']])->update($updateLog);
                    $shop_balance = ShopUser::where(['member_id'=>$log['member_id']])->value('shop_balance');
                    $trans = [
                        'member_id'=>$log['member_id'],
                        'amount'=>$log['amount'],
                        'before_balance'=>$shop_balance,
                        'after_balance'=>$shop_balance + $log['amount'],
                        'trade_no'=>$request['trade_no'],
                        'trans_type'=>ShopTrans::ORDER_TRANS_TYPE_CHARGE,
                        'create_time'=>dateFormat(time()),
                        'remarks'=>'账户充值',
                    ];
                    ShopTrans::insert($trans);
                    ShopUser::where(['member_id'=>$log['member_id']])->increment('shop_balance',$log['amount']);
                    DB::commit();
                }
            }
            echo "success";exit;
        }catch (\Exception $exception){
            DB::rollBack();
            echo "fail";exit;
        }
    }


    public function rechargeNotifys(Request $request){
        try{
            $result = $request->all();
            AlipayService::requestLog('采购金额充值回调','',$result);
            if($result['trade_status'] == 'TRADE_SUCCESS'){
                // DB::beginTransaction();
                $passback_params = urldecode($result['passback_params']);
                $log = RechargeLog::where(['out_trade_no'=>$request['out_trade_no'],'member_id'=>$passback_params])->first();
                $log = obToArray($log);
                if($log){
                    $updateLog = [
                        'trade_no'=>$request['trade_no'],
                        'status'=>RechargeLog::STATUS_SUCCESS,
                        'result'=>json_encode($result),
                    ];
                    RechargeLog::where(['id'=>$log['id']])->update($updateLog);
                    $procure_balance = ShopUser::where(['member_id'=>$log['member_id']])->select('procure_balance')->first();
                    $procure_balance = obToArray($procure_balance);
                    $trans = [
                        'member_id'=>$log['member_id'],
                        'amount'=>$log['amount'],
                        'before_balance'=>$procure_balance['procure_balance'],
                        'after_balance'=>$procure_balance['procure_balance'] + $log['amount'],
                        'trade_no'=>$request['trade_no'],
                        'trans_type'=>ShopTrans::ORDER_TRANS_TYPE_PROCURE_CHARGE,
                        'create_time'=>dateFormat(time()),
                        'remarks'=>'采购账户充值',
                    ];
                    ShopTrans::insert($trans);
                    $updateData = [
                        'procure_balance'=>$procure_balance['procure_balance'] + $log['amount']
                    ];
                    ShopUser::where(['member_id'=>$log['member_id']])->update($updateData);
                    // DB::commit();
                }
            }
            echo "success";exit;
        }catch (\Exception $exception){
            // DB::rollBack();
            echo "fail";exit;
        }
    }



    /**
     * 支付宝部分还款支付回调
     * @param Request $request
     * @throws \Exception
     */
    public function orderLeasePartialNotify(Request $request){
        $result = $request->all();
        AlipayService::requestLog('部分还款主动支付回调','',$result);
        if(!empty($result) && isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS'){
            $orderNo = explode("|",$result['out_trade_no']);
            $order = Order::from('sp_order_2 as o')->select('o.id','o.uid','o.other_order_id','o.other_user_id','o.rent_total','o.trade_no','o.mobile',
                'o.realname','o.seller_id','og.goods_title','og.imgurl','o.pay_type','o.flow_id','o.is_skip','m.cert_name','m.cert_no',
                'm.user_id','og.pact_type','o.month_total','o.is_renewal','o.parent_order_no','o.sign_no')
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->where(['trade_no' => $orderNo[0]])
                ->first();
            $order = obToArray($order);
            if(!empty($order)){
                $passback_params = urldecode($result['passback_params']);
                $leaseID =$passback_params;

                $partial['trade_no']   = $result['trade_no'];
                $partial['out_order_no'] = $result['out_trade_no'];
                $partial['pay_time']  = strtotime($result['gmt_payment']);
                $partial['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                $partial['pay_type'] = OrderLeasePartial::PAY_ALIPAY;
                //已部分还款
                $OrderLeasePartial = OrderLeasePartial::where('id',$leaseID)->where('status',OrderLease::ORDER_LEASE_STATUS_PAID)->value('status');
                $resa=OrderLeasePartial::where(['out_trade_no' => $result['out_trade_no']])->update($partial);
                if(empty($OrderLeasePartial)&&$resa){
                    OrderLease::where('id',$leaseID)->increment('paid_rent',$result['receipt_amount']);
                }
                $orderLease = OrderLease::where('id',$leaseID)->select('id','which_period','rent','paid_rent','overdue_amount')->first()->toArray();
                if($orderLease){
                    if($orderLease['which_period'] == 1){
                        $arr['status']  = OrderService::ORDER_STATUS_PAY_SUCCESS;
                        $arr['pay_time']  = time();
                        Order::where(['id' => $order['id']])->update($arr);
                    }
                    if(bcadd($orderLease['overdue_amount'],$orderLease['rent'],2)<=$orderLease['paid_rent']){
                        $leaseSave['trade_no']   = $result['trade_no'];
                        $leaseSave['out_order_no'] = $result['out_trade_no'];
                        $leaseSave['pay_time']  = strtotime($result['gmt_payment']);
                        $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;
                        OrderLease::where('id',$leaseID)->update($leaseSave);
                        //检测逾期订单状态
                        if($status = Order::checkOrderOverdueStatus($order['id'])){
                            Order::where(['id' => $order['id']])->update(['status'=>$status]);
                        }
                    }
                    if($order['pay_type'] == Order::ORDER_PAY_TYPE_ANTCHAIN){ //智能合同代扣 主动支付后取消改期代扣规则
                        $cancel_out_order_no = $order['flow_id'].'_'.$orderLease['which_period'];
                        if($orderLease['which_period']>0){
                            $lease_res = AntchainService::payRule($order['flow_id']);
                            if($lease_res['status']&&isset($lease_res['data'])&&!empty($lease_res['data'])){
                                $lease_data=json_decode($lease_res['data'],true);
                                $cancel_out_order_no=$lease_data['payRules'][$orderLease['which_period']-1]['outTradeNo'];
                                AntchainService::paysingletradeCancel($order['flow_id'],$cancel_out_order_no);
                            }

                        }
                    }
                    if($order['sign_no']){ //蚂蚁链租赁平台智能合同代扣 主动支付后取消改期代扣规则
                        AntchainAtoService::repayWithholdPlan($order['trade_no'],$orderLease['which_period'],$orderLease['rent']);
                    }
                }

                OtherWithholdLog::orderWithholdLog($order['trade_no'],$orderLease['id'],$result['out_trade_no'],$result['trade_no'],$result,OtherWithholdLog::PAY_TYPE_PREPAYMENT,true,1,$result['receipt_amount']);

                echo "success";exit;
            }
        }
        echo "fail";exit;

    }

    /**
     * 微信部分还款支付回调
     * @param Request $request
     * @throws \Exception
     */
    public function wechatNativePayNotify(Request $request){
        $data = WechatService::notices();
        WechatService::requestLog('微信支付回调','',$data);
        if($data['return_code'] == 'SUCCESS'){
            $orderNo = explode('|',$data['out_trade_no']);//支付lease_id
            $order = Order::from('sp_order_2 as o')->select('o.id','o.uid','o.other_order_id','o.other_user_id','o.rent_total','o.trade_no','o.mobile','o.realname','o.seller_id','og.goods_title','og.imgurl','o.pay_type','o.flow_id','o.is_skip','m.cert_name','m.cert_no','m.user_id','og.pact_type','o.month_total','o.is_renewal','o.parent_order_no')
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->where(['trade_no' => $orderNo[0]])
                ->first();
            $order = obToArray($order);
            if(!empty($order)){
                $leaseID= $data['attach'];

                $partial['trade_no']   = $data['out_order_no'];
                $partial['out_order_no'] = $data['transaction_id'];
                $partial['pay_time']  = strtotime($data['time_end']);
                $partial['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                $partial['pay_type'] = OrderLeasePartial::PAY_WXPAY;
                //已部分还款
                $OrderLeasePartial = OrderLeasePartial::where('id',$leaseID)->where('status',OrderLease::ORDER_LEASE_STATUS_PAID)->value('status');
                $resa=OrderLeasePartial::where(['out_trade_no' => $data['out_trade_no']])->update($partial);
                if(empty($OrderLeasePartial)&&$resa){
                    //增加部分还款金额
                    OrderLease::where('id',$leaseID)->increment('paid_rent',$data['total_fee']/100);
                }
                $orderLease = OrderLease::where('id',$leaseID)->select('id','which_period','rent','paid_rent','overdue_amount')->first()->toArray();
                if($orderLease){
                    if($orderLease['which_period'] == 1){
                        $arr['status']  = OrderService::ORDER_STATUS_PAY_SUCCESS;
                        $arr['pay_time']  = time();
                        Order::where(['id' => $order['id']])->update($arr);
                    }
                    if(bcadd($orderLease['overdue_amount'],$orderLease['rent'],2)<=$orderLease['paid_rent']){
                        $leaseSave['out_order_no']   = $data['out_trade_no'];
                        $leaseSave['out_order_no'] = $data['transaction_id'];
                        $leaseSave['pay_time']  = strtotime($data['time_end']);
                        $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_WECHAT;
                        OrderLease::where('id',$leaseID)->update($leaseSave);
                        //检测逾期订单状态
                        if($status = Order::checkOrderOverdueStatus($order['id'])){
                            Order::where(['id' => $order['id']])->update(['status'=>$status]);
                        }
                    }

                    if($order['pay_type'] == Order::ORDER_PAY_TYPE_ANTCHAIN){ //智能合同代扣 主动支付后取消改期代扣规则
                        $cancel_out_order_no = $order['flow_id'].'_'.$orderLease['which_period'];
                        if($orderLease['which_period']>0){
                            $lease_res = AntchainService::payRule($order['flow_id']);
                            if($lease_res['status']&&isset($lease_res['data'])&&!empty($lease_res['data'])){
                                $lease_data=json_decode($lease_res['data'],true);
                                $cancel_out_order_no=$lease_data['payRules'][$orderLease['which_period']-1]['outTradeNo'];
                                AntchainService::paysingletradeCancel($order['flow_id'],$cancel_out_order_no);
                            }
                        }
                    }
                    if($order['sign_no']){ //蚂蚁链租赁平台智能合同代扣 主动支付后取消改期代扣规则
                        AntchainAtoService::repayWithholdPlan($order['trade_no'],$orderLease['which_period'],$orderLease['rent']);
                    }
                }

                OtherWithholdLog::orderWithholdLog($order['trade_no'],$orderLease['id'],$data['out_trade_no'],$data['transaction_id'],$data,OtherWithholdLog::PAY_TYPE_WXPAY,true,1,$data['total_fee']/100);

                echo "success";exit;
            }
        }
        echo "fail";exit;
    }




    /**
     * e签宝四方合同签署回调-商户平台
     */
    public function esignNotify(Request $request){
        $request_data = $request->all();
        WechatService::requestLog('e签宝四方合同签署回调-商户平台','',$request_data);
        $flow_id = $request_data['flowId'];
        $order = Order::from('sp_order_2 as o')
            ->where('o.flow_id',$flow_id)
            ->leftjoin('sp_member_2 as u','o.uid','u.id')
            ->leftjoin('sp_shop_user_2 as su','o.seller_id','su.member_id')
            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
            ->leftjoin('sp_goods_2 as g','og.goods_id','g.id')
            ->select(
                'o.id','o.trade_no','o.begin_time','o.zulinbao_order_id','o.end_time','o.pact_url_3','o.pact_url','o.uid','o.seller_id','o.is_insurance_choose',
                'o.flow_id','o.mobile','o.user_email','o.sign_num','o.address','o.rent_total','o.month_total','o.amount','o.realname','o.rent_total',
                'o.foregift','o.status','o.prov','o.city','o.area','o.sign_status','o.is_rent_choose'
                ,'o.create_time'
                ,'u.ant_user_id','u.mobile as user_mobile','u.id as x_user_id','u.cert_name','u.user_id','u.cert_no','u.esign_user_id'
                ,'u.idcard_front','u.idcard_back','og.id as order_goods_id ','og.pact_type','og.is_buy_out','og.goods_title','og.setmeal_title',
                'og.lease_set','og.setmeal_price','og.setmeal_foregift','o.prepayment_total',
                'og.goods_id','og.setmeal_id','og.id as order_goods_id','og.spec_id','og.lease_price','og.lease_time','og.website_price','og.start_date'
                ,'su.mechanism','su.faname','su.shopname','su.contact_tel','su.company','su.company_area','su.companyid','su.id as shop_user_id'
                ,'su.ant_user_id as mer_ant_id','o.sign_no','su.esign_seal_id','su.ant_seal_id','o.prepayment_total' ,'g.new_grade')
            ->first();
        $order = $order ? $order->toArray() : [];

        if(!empty($order)){
            if($order['sign_status'] == EsignService::ESIGN_STATUS_DRAFT || $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING){

                if($request_data['action'] == 'SIGN_FLOW_FINISH'){
                    //合同下载
                    $return_content = EsignService::downloadDocument($flow_id);
                    if($return_content && !empty($return_content['fileUrl'])){
                        $fileUrl = $return_content['fileUrl'];
                        $fileName = $flow_id.".pdf";
                        $file = file_get_contents($fileUrl);
                        $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

                        file_put_contents($path,$file);
                        $uploud_res = AlipayService::upload($fileName,$path);
                        if($uploud_res['status']){
                            if(file_exists($path)){
                                unlink($path);
                            }
                        }
                        $order_sign['pact_four_url'] = $fileName;
                        $order_sign['four_sign_status']  = EsignService::ESIGN_STATUS_FINISH;
                        Order::where('id',$order['id'])->update($order_sign);

                        $order['pact_url'] = $fileName;
                        NotarizeService::uploadOrderInfo($order);
                        return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
                    }else{
                        return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
                    }
                }
            }else{
                return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
            }
        }else{
            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
        }
    }


    /**
     * 微信支付宝账单流水报告回调
     */
    public function billProcessBack(Request $request){
        $request_data = $request->all();
        WechatService::requestLog('微信支付宝账单流水报告回调','',$request_data);
        $res=false;
        if($request_data['mailId']&&$request_data['receiver']){
            $res=BillReport::insertReport($request_data);
        }
        if($res){
            return json_encode(['success'=>true]);
        }
    }


    // qn风控结果回调
    public function accurateRisk(Request $request){
        $request_data = $request->all();
        WechatService::requestLog('qn风控结果回调','',$request_data);
        $res=false;
        if($request_data['flowNo']&&$request_data['result']){
            $res=MemberQnRisk::where('flowNo',$request_data['flowNo'])->update(['risk_result'=>$request_data['result'],'risk_level'=>$request_data['riskLevel']??'']);
        }
        if($res){
            return true;
        }
        return false;
    }

}
